package job.work.framework;

import com.google.common.collect.ImmutableMap;
import job.work.domain.course.TokenIsExpiredException;
import job.work.domain.response.AuthCode;
import job.work.domain.response.CommonCode;
import job.work.domain.response.ResponseResult;
import job.work.domain.response.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常捕获类
 *
 * @author Administrator
 * @version 1.0
 * @create 2018-09-14 17:32
 **/
@ControllerAdvice
public class ExceptionCatch {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatch.class);

    /**
     * 定义map，配置异常类型所对应的错误代码
     */
    private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;
    /**
     * 定义map的builder对象，去构建ImmutableMap
     */
    protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder();


    @ResponseBody
    @ResponseStatus(code = HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        Map<String, Object> resultMap = new HashMap<>(8);
        e.getBindingResult().getAllErrors().forEach(error -> {
            FieldError fieldError = (FieldError)error;
            resultMap.put(fieldError.getField(),fieldError.getDefaultMessage());

        });
        return new ResponseResult<>(CommonCode.FAIL,resultMap);
    }


    @ResponseBody
    @ResponseStatus(code = HttpStatus.OK)
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseResult handlerConstraintViolationException(ConstraintViolationException e) {
        return new ResponseResult<>(CommonCode.FAIL,e.getMessage());
    }

    @ResponseBody
    @ResponseStatus(code = HttpStatus.OK)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseResult handlerConstraintViolationException(MissingServletRequestParameterException e) {
        return new ResponseResult<>(CommonCode.FAIL,e.getMessage());
    }

    /**
     * 捕获CustomException此类异常
     *
     * @param customException
     * @return
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult customException(CustomException customException) {
        //记录日志
        LOGGER.error("catch exception:{}", customException.getMessage());
        ResultCode resultCode = customException.getResultCode();
        return new ResponseResult<>(resultCode);
    }

    /**
     * 捕获Exception此类异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception exception) {
        //记录日志
        LOGGER.error("catch exception:{}", exception.getMessage());
        if (EXCEPTIONS == null) {
            EXCEPTIONS = builder.build();
        }
        //从EXCEPTIONS中找异常类型所对应的错误代码，如果找到了将错误代码响应给用户，如果找不到给用户响应99999异常
        ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
        if (resultCode != null) {
            return new ResponseResult<>(resultCode);
        } else {
            //返回99999异常
            System.out.println("打印异常信息" + exception.getMessage());
            return new ResponseResult<>(CommonCode.SERVER_ERROR);
        }
    }

    static {
        //定义异常类型所对应的错误代码
        builder.put(HttpMessageNotReadableException.class, CommonCode.INVALID_PARAM);
        builder.put(AccessDeniedException.class, CommonCode.UNAUTHORISE);
        builder.put(TokenIsExpiredException.class, AuthCode.AUTH_LOGIN_TOKEN_TIME);
        builder.put(IllegalArgumentException.class, AuthCode.AUTH_LOGIN_TOKEN_TIME);

    }
}
